/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * userScreen.java
 *
 * Created on Mar 30, 2011, 4:45:33 PM
 */

package forumGUI;

import client.ForumClientListener;
import client.TcpClient;
import forum.Forum;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import messaage.*;
import utils.LogHelper;

/**
 * 
 * @author Olga
 */
public class forumsScreen extends javax.swing.JFrame implements
		client.MessagesListener {

	private DefaultListModel forumsListModel;
        private boolean isModerator;
	private TcpClient client;
	private String username;
	private List<Forum> forums;

	/**
	 * After calling the constructor, creator must to set listener with
	 * constructed object. And then, creator must send GetListOfForumsMsg to the
	 * server. Otherwise, the response message GotListOfForumsMsg might be
	 * missed.
	 * 
	 * @param _client
	 * @param _username
	 */
	public forumsScreen(TcpClient _client, String _username, boolean _isModerator) {
		initComponents();
		System.out.println("forumsScreen(TcpClient _client, String _username, boolean _isModerator) ");
		this.client = _client;
		this.username = _username;
		this.forums = null;
                this.isModerator = _isModerator;
		// set model to list
		this.forumsListModel = new DefaultListModel();
		this.forumsList.setModel(this.forumsListModel);
                if (!this.isModerator){
                      this.removeForumButton.setVisible(false);
                      this.addForumButton.setVisible(false);
            }
                this.setBackground();


	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ForumsLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        forumsList = new javax.swing.JList();
        ShowButton = new javax.swing.JButton();
        logoutButton = new javax.swing.JButton();
        friendsButton = new javax.swing.JButton();
        addForumButton = new javax.swing.JButton();
        removeForumButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                windowClosed(evt);
            }
        });

        ForumsLabel.setFont(new java.awt.Font("Viner Hand ITC", 0, 48));
        ForumsLabel.setText("Forums");

        forumsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(forumsList);

        ShowButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        ShowButton.setText("Show");
        ShowButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ShowButtonActionPerformed(evt);
            }
        });

        logoutButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        logoutButton.setText("Logout");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });

        friendsButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        friendsButton.setText("Friends list");
        friendsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                friendsButtonActionPerformed(evt);
            }
        });

        addForumButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        addForumButton.setText("Add forum");
        addForumButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addForumButtonActionPerformed(evt);
            }
        });

        removeForumButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        removeForumButton.setText("Remove forum");
        removeForumButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeForumButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(72, 72, 72)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ForumsLabel)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(ShowButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(logoutButton))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(friendsButton, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                    .addComponent(addForumButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(removeForumButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ForumsLabel)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(friendsButton)
                        .addGap(18, 18, 18)
                        .addComponent(addForumButton)
                        .addGap(18, 18, 18)
                        .addComponent(removeForumButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ShowButton)
                    .addComponent(logoutButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

        private void addForumButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addForumButtonActionPerformed
            addForumScreen afs = new addForumScreen(this.client, this.username, this);
            afs.setVisible(true);
            this.setEnabled(false);
        }//GEN-LAST:event_addForumButtonActionPerformed

        private void ShowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShowButtonActionPerformed
            int selectedForumIndex = this.forumsList.getSelectedIndex();
            Forum f = this.forums.get(selectedForumIndex);
            // create new threads screen
		ThreadsScreen ts = new ThreadsScreen(this.client, this.username, this.isModerator, f.getID(), f.getSubject());
		// adds new listener to socket
		((ForumClientListener) this.client.getListener()).getConnector()
				.addListener(ts);
		// send getForumTopics msg
		this.client.sendMessage(new GetForumTopicsMsg(this.username, f.getID()+""));
		((ForumClientListener) this.client.getListener()).getConnector().removeListener(this);
		this.setVisible(false);
        }//GEN-LAST:event_ShowButtonActionPerformed

	private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_logoutButtonActionPerformed
		LogoutMsg msg = new LogoutMsg(username);
		this.client.sendMessage(msg);
	}// GEN-LAST:event_logoutButtonActionPerformed

	private void removeForumButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeForumButtonActionPerformed
		int index = this.forumsList.getSelectedIndex();
		String forumID = this.forums.get(index).getID() + "";
		this.client.sendMessage(new RemoveForumMsg(this.username, forumID));
	}// GEN-LAST:event_removeForumButtonActionPerformed

	private void friendsButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_friendsButtonActionPerformed
		// create new friendsScreen
		friendsScreen fs = new friendsScreen(this.client, this.username, this.isModerator);
		// adds new listener to socket
		((ForumClientListener) this.client.getListener()).getConnector()
				.addListener(fs);
		// send getFriens msg
		this.client.sendMessage(new GetFriendsListMsg(this.username));
        ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
        tempListener.getConnector().removeListener(this);
		this.setVisible(false);
	}// GEN-LAST:event_friendsButtonActionPerformed

              public void setBackground()
    {
        Container con =this.getContentPane();
        JPanel panelBgImg;
        con.setLayout(null);
        final String photoPath = "src/images/screen.jpg";

        ImageIcon imh = new ImageIcon(photoPath);
//        setSize(imh.getIconWidth(), imh.getIconHeight());

        panelBgImg = new JPanel()
        {
            public void paintComponent(Graphics g)
            {
                Image img = new ImageIcon(photoPath).getImage();

                Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                setPreferredSize(size);
                setMinimumSize(size);
                setMaximumSize(size);
                setSize(size);
                setLayout(null);
                g.drawImage(img, 0, 0, null);
            }
        };

        con.add(panelBgImg);
        panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());

    }
	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				// new forumsScreen().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ForumsLabel;
    private javax.swing.JButton ShowButton;
    private javax.swing.JButton addForumButton;
    private javax.swing.JList forumsList;
    private javax.swing.JButton friendsButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton logoutButton;
    private javax.swing.JButton removeForumButton;
    // End of variables declaration//GEN-END:variables
	@Override
	public void connected(ConnectedMsg msg) {
	}

	@Override
	public void disconnected(DisconnectedMsg msg) {
		// TODO Implement disconnected msg in forumsScreen 

	}

	@Override
	public void errorMessage(ErrorMsg msg) {
		String body = msg.getBody();
		JOptionPane.showMessageDialog(this, body);
	}

	@Override
	public void registered(RegisteredMsg msg) {
	}

	@Override
	public void loggedIn(LoggedInMsg msg) {
	}

	@Override
	public void loggedOff(LoggedOffMsg msg) {
		this.setVisible(false);
		MainScreen ms = new MainScreen(client);
		ms.setVisible(true);
	}

	@Override
	public void gotListOfForums(GotListOfForumsMsg msg) {
		
		System.out.println("gotListOfForums(GotListOfForumsMsg msg)");
		this.forums = msg.getListOfForums();
		for (Forum f : this.forums)
			this.forumsListModel.addElement(f.getSubject());
		this.setVisible(true);
	}

	@Override
	public void gotTopicsOfForum(GotTopicsOfForumMsg msg) {
	}

	@Override
	public void gotThread(GotThreadMsg msg) {
	}

	@Override
	public void addedPost(AddedPostMsg msg) {
	}

	@Override
	public void createdThread(CreatedThreadMsg msg) {
	}

	@Override
	public void addedForum(AddedForumMsg msg) {
            if (msg.isFriend())
                JOptionPane.showMessageDialog(this, msg.getUsername()+" added forum "+msg.getSubject());
            this.forums.add(new Forum(msg.getForumID(), msg.getSubject()));
            this.forumsListModel.addElement(msg.getSubject());
	}

	@Override
	public void removedForum(RemovedForumMsg msg) {
            //TODO: add notification to friend about removed forum
		int removedForumID = msg.getForumID();
		int index = -1;
		for (int i = 0; i < this.forums.size(); i++)
			if (this.forums.get(i).getID() == removedForumID) {
				index = i;
				break;
			}
		if (index >= 0) {
			this.forums.remove(index);
			this.forumsListModel.remove(index);
		} else
			LogHelper.instance().log(
					"Cannot remove forum with id " + removedForumID
							+ " from client. It not found.");
	}

	@Override
	public void editedPost(EditedPostMsg msg) {
	}

	@Override
	public void removedUser(RemovedUserMsg msg) {
		if (msg.getUsernameToRemove().equalsIgnoreCase(this.username)){
                    JOptionPane.showMessageDialog(this, "Sorry, but you was just removed from the forum :(");
                    ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
                    tempListener.getConnector().removeListener(this);
                    this.dispose();
            }
	}

	@Override
	public void removedThread(RemovedThreadMsg msg) {
	}

	@Override
	public void removedPost(RemovedPostMsg msg) {
	}

	@Override
	public void addedFriend(AddedFriendMsg msg) {
	}

	@Override
	public void removedFriend(RemovedFriendMsg msg) {
	}

	@Override
	public void gotFriendsList(GotFriendsListMsg msg) {
	}

}
